package com.kinon.norogamilk.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.RadioButton;

import com.kinon.norogamilk.R;
import com.kinon.norogamilk.bean.RaodBean;

import java.util.ArrayList;
import java.util.Locale;

/**
 * Created by lhqq on 2018-01-18.
 */

public class RaodAdapter extends BaseAdapter {

    private ArrayList<RaodBean> list;
    private Context mContext;
    private int lastPosition = 0;
    private GridView mGridView;

    public RaodAdapter(ArrayList<RaodBean> list, Context mContext) {
        this.list = list;
        this.mContext = mContext;
    }

    public RaodAdapter(GridView mGridView, Context mContext, ArrayList<RaodBean> list) {
        this.mGridView = mGridView;
        this.mContext = mContext;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(R.layout.item_road_layout, null);
            holder.tv_raodName = view.findViewById(R.id.tv_roadName);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        holder.tv_raodName.setText(String.format(Locale.getDefault(), "货道%d", i));
        updateBackground(i, holder.tv_raodName);
        return view;
    }

    @SuppressLint("NewApi")
    public void updateBackground(int position, RadioButton view) {

        if (mGridView.isItemChecked(position)) {
            mGridView.setItemChecked(lastPosition, false);
            lastPosition = position;
        }
        if (lastPosition == position) {
            view.setChecked(true);
        } else {
            view.setChecked(false);
        }

    }

    private class ViewHolder {
        RadioButton tv_raodName;
    }
}
